const fs = require('fs')
const path = require('path')
const {db,pool}=require('../db/db')
const goodsSQL = require('../db/goodsSQL')

const getList = async (c, p, s, campuls, st, sortT, sortM, category) => {
  let result = await db(goodsSQL.queryAll, [])
  let data=JSON.stringify(result)
  let list = JSON.parse(data)
  if (category) list = list.filter(item => item.category === category)
  if (s) list = list.filter(item => item.title.search(s) !== -1 ||item.price.search(s) !== -1)
  if(campuls) list = list.filter(item => item.campuls === campuls)
  if (st !== '100%') list = list.filter(item => item.quality_type === st)

  switch (sortT) {
    case 'id': list.sort((a, b) => sortM === 'ASC' ? a.goods_id - b.goods_id : b.goods_id - a.goods_id); break
    case 'price': list.sort((a, b) => sortM === 'ASC' ? a.price - b.price : b.price - a.price); break
    case 'quality': list.sort((a, b) => sortM === 'ASC' ? parseFloat(a.quality_Type).toFixed(1) - parseFloat(b.quality_Type).toFixed(1) : parseFloat(b.quality_Type).toFixed(1) - parseFloat(a.quality_Type).toFixed(1)); break
  }

  return {
    list: list.slice((c - 1) * p, c * p),
    total: Math.ceil(list.length / p)
  }
}

const getGoodsById = async (goodsId) => {
  let result = await db(goodsSQL.queryAll, [])
  let data=JSON.stringify(result)
  return JSON.parse(data).find(item => item.goods_id === goodsId)
}

const category = async () => {
  let result = await db(goodsSQL.queryAll, [])
  let data=JSON.stringify(result)
  const goods = JSON.parse(data)
  const arr = []

  goods.forEach(item => arr.push(item.category))

  return [ ...new Set(arr) ]
}
const campuls = async () => {
  let result = await db(goodsSQL.queryAll, [])
  let data=JSON.stringify(result)
  const goods = JSON.parse(data)
  const arr = []

  goods.forEach(item => arr.push(item.campuls))

  return [ ...new Set(arr) ]
}

module.exports = {
  getList,
  getGoodsById,
  category,
  campuls
}
